<?php

namespace app\common\model\goods;

use app\common\model\Order;
use app\common\model\order\Goods;
use think\Db;
use think\Model;


class Review extends Model
{





    // 表名
    protected $name = 'goods_review';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'images_array',
    ];
    public function getCreatetimeAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getImagesArrayAttr($value, $data)
    {
        if ($data['images']) {
            $arr = explode(',', $data['images']);
            foreach ($arr as &$v) {
                $v = cdnurl($v, true);
            }
            return $arr;
        }
        return [];
    }
    public function goods()
    {
        return $this->belongsTo('app\common\model\Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function order()
    {
        return $this->belongsTo('app\common\model\Order', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function addReview($data, $uid)
    {
        extract($data);
        Db::startTrans();
        try {
            $goods = Goods::where('order_id', $order_id)->where('goods_id', $goods_id)->find();
            if($goods['is_comment']==1)
            {
                exception('商品已评论');
            }
            $res = Goods::where('order_id', $order_id)->where('goods_id', $goods_id)->update(['is_comment' => 1]);
            if ($res) {
                $data = [
                    'user_id' => $uid,
                    'goods_id' => $goods_id,
                    'description' => $description,
                    'images' => $images,
                    'order_id' => $order_id,
                ];
                $this->save($data);
            }
            $num = Goods::where('order_id', $order_id)->where('is_comment', 0)->count();
            if ($num == 0) {
                $order = new Order;
                $order->save(['is_comment' => 1, 'status' => 4], ['id' => $order_id]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return true;
    }
}
